// pages/car_ctl/car_ctl.js
var app = getApp();
var udp = null;
var timer_Id = 0;
var car_json =  {          
  device_id: 'car',
  command: 'setstate',
  parameter:{
    mode:'manual',
    state:'stop',
    beep:'off',
    led3:'off',
    speed:500,
  }
};

Page({
  /**
   * 页面的初始数据
   */
  data: {
    speed: 500,               //默认速度值
    electric: 3,              //电池电压
  },
  car_state_run()             //前进
  {
    car_json.parameter.state = "run";
    this.Control_car_start();
  },
  car_state_left()            //左转
  {
    car_json.parameter.state = "left";
    this.Control_car_start();
  },
  car_state_right()           //右转
  {
    car_json.parameter.state = "right";
    this.Control_car_start();
  },
  car_state_back()            //后退
  {
    car_json.parameter.state = "back";
    this.Control_car_start();
  },
  car_beep()                  //开喇叭
  {
    if (car_json.parameter.beep == "off")
    {
      car_json.parameter.beep = "on";
    }
    else
    {
      car_json.parameter.beep = "off";
    }
    this.udp_send_data();
  },
  car_led3_white()            //三色灯 白灯
  {
    car_json.parameter.led3 = 'white';
    this.udp_send_data();
  },
  car_led3_red()              //三色灯 红灯
  {
    car_json.parameter.led3 = 'red';
    this.udp_send_data();
  },
  car_led3_off()              //三色的 关灯
  {
    car_json.parameter.led3 = 'off';
    this.udp_send_data();
  },
  Control_car_start()         //开始发送控制命令给小车
  {
    timer_Id = setInterval(()=>{
      //console.log('测试');
      this.udp_send_data();
    }, 300)
  },
  Control_car_stop()          //停止发送
  {
    clearInterval(timer_Id);
  },
  car_stop()
  {
    car_json.parameter.speed = 300;
    car_json.parameter.state = "stop";
    this.udp_send_data();
  },
  car_speed_up()              //加速
  {
    timer_Id = setInterval(()=>{
      car_json.parameter.speed += 25;
      if (car_json.parameter.speed >= 1000) {
        car_json.parameter.speed = 1000;
      }
      //console.log('测试');
      this.udp_send_data();
    }, 300)
  },
  car_speed_down()          //刹车
  {
    timer_Id = setInterval(()=>{
      car_json.parameter.speed -= 100;
      if (car_json.parameter.speed <= 300) {
        car_json.parameter.speed = 300;
        car_json.parameter.state = "stop";
      }
      //console.log('测试');
      this.udp_send_data();
    }, 300)
  },
  udp_send_data()
  {
    let jsonString = JSON.stringify(car_json);
    console.log("send massage:");
    console.log(jsonString);
    udp.send({
      address: app.my_data.server_ip,
      port: app.my_data.server_port,
      message: jsonString,
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    udp = app.my_data.udp;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    udp.onMessage((res)=>{
      var buffer = res.message;
      var dataview = new DataView(buffer);
      var ints = new Uint8Array(buffer.byteLength);
      var str = '';
      for (var i = 0; i < ints.length; i++) {
        str += String.fromCharCode(dataview.getUint8(i));
      }
      console.log("message:"+str);
      let jsObject;
      try {
        jsObject = JSON.parse(str);
        console.log(jsObject);  //控制台打印提示
      } catch (error) {
        console.error("Error parsing JSON:", error);
        return;
      } finally {
        this.setData({
          speed: jsObject["parameter"]["speed"],
          electric: jsObject["parameter"]["electric"]
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    udp.offMessage();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})